﻿using Max.PH5_2103A.Shopping.TEntityFrame.Domain;
using Max.PH5_2103A.Shopping.TEntityFrame.IRepository;
using Max.PH5_2103A.Shopping.TEntityFrame.IService;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Max.PH5_2103A.Shopping.TEntityFrame.Service
{
    public class MemberAddressService : BaseService<MemberAddressEntity>, IMemberAddressService
    {
        IMemberAddressRepository _repository;
        IUnitOfWork _unitOfWork;
        public MemberAddressService(IMemberAddressRepository repository, IUnitOfWork unitOfWork) : base(repository, unitOfWork)
        {
            _repository = repository;   
            _unitOfWork = unitOfWork;
        }


        public override int Insert(MemberAddressEntity entity)
        {
            using (var tran = _unitOfWork.GetContext().Database.BeginTransaction()) //开启事务
            {
                try
                {
                    //前提：前台要添加的数据选中是是默认地址
                    if(entity.IsDefault)
                    {
                        //先修改：把这些地址中，本身是默认的地址，修改为非默认地址
                        var m =_repository.Select().Where(x => x.MemberId == entity.MemberId && x.IsDefault).FirstOrDefault();
                        if(m != null)
                        {
                            m.IsDefault = false;
                            _repository.Update(m);
                        }
                    }
                    //后添加
                    _repository.Insert(entity);

                    _unitOfWork.SaveChanges();

                    tran.Commit(); //提交事务

                    return 1;
                }
                catch (Exception)
                {
                    tran.Rollback(); //回滚事务
                    throw;
                }
            }

            return 0;
        }
    }
}
